<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入协会名称" />
      <el-input v-model="listQuery.code" clearable class="filter-item" style="width: 200px;" placeholder="请输入协会编号" />
      <el-button
        v-permission="['user:association:list']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter">查找</el-button>
      <!--添加协会-->
      <el-button
        v-permission="['user:association:create']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate">添加</el-button>
      <el-button
        v-permission="['user:association:batchdelete']"
        :disabled="selectedIds.length === 0"
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="协会编号" prop="id" />
      <el-table-column align="center" label="协会名称" prop="name" />
      <el-table-column align="center" label="协会logo" width="80" prop="logoUrl">
        <template slot-scope="scope">
          <el-popover placement="right" trigger="hover">
            <img :src="scope.row.logoUrl" height="230">
            <img slot="reference" :src="scope.row.logoUrl" height="23">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column align="center" label="简介" prop="introduction">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="showDetail(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="成立时间" prop="dateOfEstablishment" />
      <el-table-column align="center" label="负责人" prop="principal" />
      <el-table-column align="center" label="地址" prop="address" />
      <el-table-column align="center" label="联系人" prop="contact" />
      <el-table-column align="center" label="联系电话" prop="phone" />
      <el-table-column align="center" label="备注" prop="remark" />
      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-permission="['user:association:detail']"
            type="primary"
            size="mini"
            @click="handleDetail(scope.row)">
            详情</el-button>
          <el-button
            v-permission="['user:association:update']"
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)">
            编辑</el-button>
          <el-button
            v-permission="['user:association:delete']"
            type="danger"
            size="mini"
            @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList" />
    <!-- 查看协会简介 -->
    <div class="introduction">
      <el-dialog :visible.sync="detailDialogVisible" title="协会简介" style="text-align: center;">
        <div class="contentRecord" v-html="introductionText" />
      </el-dialog>
    </div>
    <!-- 添加/修改/详情对话框  -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      top="5vh"
      style="margin-top: -30px;"
      width="900px">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="协会基本信息" name="first">
          <el-form ref="formData" :model="formData" :rules="rules" label-width="80px" style="margin:10px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="协会名称" prop="name">
                  <el-input v-model="formData.name" :disabled="dialogStatus == 'detail'" placeholder="请输入协会名称" />
                </el-form-item>
                <el-form-item label="联系人" prop="contact">
                  <el-input v-model="formData.contact" :disabled="dialogStatus == 'detail'" placeholder="请输入联系人" />
                </el-form-item>
                <el-form-item label="地址" prop="address">
                  <el-input v-model="formData.address" :disabled="dialogStatus == 'detail'" placeholder="请输入地址" />
                </el-form-item>
                <el-form-item label="成立时间" prop="dateOfEstablishment">
                  <el-date-picker
                    v-model="formData.dateOfEstablishment"
                    :disabled="dialogStatus == 'detail'"
                    type="date"
                    placeholder="选择日期" />
                </el-form-item>
              </el-col>
              <el-col :span="12" style="padding-left: 20px;">
                <el-form-item label="负责人" prop="principal">
                  <el-input v-model="formData.principal" :disabled="dialogStatus == 'detail'" placeholder="请输入负责人" />
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="formData.phone" :disabled="dialogStatus == 'detail'" placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item label="官网地址" prop="url">
                  <el-input v-model="formData.url" :disabled="dialogStatus == 'detail'" placeholder="请输入官网地址" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="formData.remark" :disabled="dialogStatus == 'detail'" placeholder="请输入备注" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="协会logo" prop="logoUrl">
              <el-upload
                :disabled="dialogStatus == 'detail'"
                :action="uploadPath"
                :headers="headers"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeFileUplod"
                class="avatar-uploader"
                accept=".jpg, .jpeg, .png, .gif">
                <img v-if="formData.logoUrl" ref="adImg" :src="formData.logoUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
              <div v-if="formData.logoUrl" class="logoUrlIcon" style="">
                <i class="el-icon-zoom-in" style="font-size: 30px;margin-right: 10px;color: #fff;" @click="bigImg"/>
                <i class="el-icon-delete" style="font-size: 30px;color: #fff;" @click="deleteImg"/>
              </div>
            </el-form-item>
            <el-form-item v-if="dialogStatus == 'create' || dialogStatus == 'update'" label="协会简介" prop="introduction">
              <editor :init="editorInit" v-model="formData.introduction" style="min-height: 200px;" />
            </el-form-item>

          </el-form>
          <div
            v-if="dialogStatus == 'create' || dialogStatus == 'update'"
            style="margin-left: 700px;margin-bottom: 10px;">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">确定</el-button>
            <el-button v-else type="primary" @click="updateData">确定</el-button>
          </div>
        </el-tab-pane>
        <!--添加成员-->
        <el-tab-pane v-if="dialogStatus == 'update' || dialogStatus == 'detail'" label="企业成员" name="second">
          <!-- <div v-show="showInformation == 2"> -->
          <el-button
            v-if="dialogStatus == 'update'"
            :plain="true"
            type="primary"
            style="margin-left: 15px;margin-top:10px;"
            @click="handleAttributeShow">邀请</el-button>
          <el-table v-if="dialogStatus == 'update' || dialogStatus == 'detail'" :data="addList">
            <el-table-column property="name" label="成员姓名" />
            <el-table-column property="phone" label="手机号码" />
            <el-table-column
              v-if="dialogStatus == 'update'"
              align="center"
              label="操作"
              width="100"
              class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button type="danger" size="mini" @click="handleAttributeDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.limit"
            @pagination="getDetailAssociation" />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 协会logo放大框 -->
    <el-dialog :visible.sync="dialogVisible" :show-close="false">
      <img :src="formData.logoUrl" width="100%">
    </el-dialog>
    <el-dialog :visible.sync="addDialogVisible" :before-close="handleClose" width="600px">
      <div>
        <h3>企业二维码</h3>
        <div id="qrcode" ref="qrcode" />
      </div>
      <h3>企业链接</h3>
      <div style="display: flex;">
        <el-input id="link" ref="link" :value="url" type="text" readonly />
        <el-button
          class="btn"
          type="primary"
          style="margin-left: 10px;"
          data-clipboard-action="copy"
          data-clipboard-target="#link"
          @click="copyLink">复制</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Clipboard from 'clipboard'
import { listAssociation, createAssociation, updateAssociation, deleteAssociation, detailAssociation, batchDeleteAssociation, richTextAssociation, queryAssociation, deleteUser } from '@/api/association'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import Editor from '@tinymce/tinymce-vue'
import { uploadPath, beforeFileUplod, createStorage } from '@/api/storage'
import { getToken } from '@/utils/auth'
import QRCode from 'qrcodejs2'

export default {
  name: 'Association',
  components: { Pagination, Editor },
  data() {
    return {
      showInformation: 1,
      url: 'https://first-1300696665.cos.ap-nanjing.myqcloud.com/commons/a3cdd0a4680f4e54856ad0eb247df3cf.jpg',
      uploadPath,
      beforeFileUplod,
      list: [],
      total: 0,
      introductionText: '',
      selectedIds: [],
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        code: undefined
      },
      formData: {
        dateOfEstablishment: undefined,
        name: undefined,
        phone: undefined,
        principal: undefined,
        contact: undefined,
        address: undefined,
        url: undefined,
        remark: undefined,
        introduction: '',
        logoUrl: undefined
      },
      // 放大图片
      dialogVisible: false,
      detailDialogVisible: false,
      textMap: { update: '编辑', create: '创建', detail: '详情' },
      dialogFormVisible: false,
      dialogStatus: '',
      activeName: 'first',
      rules: {
        name: [{ required: true, message: '协会名称不能为空', trigger: 'blur' }],
        phone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }, { pattern: /^1[3456789]\d{9}$/, message: '请输入正确电话' }],
        principal: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
        contact: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
        dateOfEstablishment: [{ required: true, message: '请选择日期', trigger: 'blur' }],
        address: [{ required: true, message: '地址不能为空', trigger: 'blur' }],
        logoUrl: [{ required: true, message: '请选择图片', trigger: 'blur' }],
        introduction: [{ required: true, message: '协会简介不能为空', trigger: 'blur' }]
      },
      // 展示邀请的弹出框
      addDialogVisible: false,
      editorInit: {
        language: 'zh_CN',
        convert_urls: false,
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData).then(res => {
            success(res.data.url)
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      },
      addList: []
    }
  },
  computed: {
    headers() {
      return {
        ADMINTOKEN: getToken()
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listAssociation(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleSelectionChange(e) {
      const temp = []
      e.forEach(item => {
        temp.push(item.id)
      })
      this.selectedIds = temp
    },
    handleBatchDelete(e) {
      // 执行批量删除
      this.$confirm(
        '此操作将永久删除选中的' +
        this.selectedIds.length +
        '件商品, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          batchDeleteAssociation(this.selectedIds)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '删除成功'
              })
              this.getList()
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        })
        .catch(() => {
          return false
        })
    },
    resetForm() {
      this.formData = {
        dateOfEstablishment: undefined,
        name: undefined,
        phone: undefined,
        principal: undefined,
        contact: undefined,
        address: undefined,
        url: undefined,
        remark: undefined,
        introduction: '',
        logoUrl: undefined
      }
    },
    handleClick(tab, event) {
    },
    // 查看协会简介
    showDetail(row) {
      richTextAssociation(row.id)
        .then(response => {
          this.detailDialogVisible = true
          this.introductionText = response.data.data
        })
        .catch(response => {
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCreate() {
      this.resetForm()
      this.addList = []
      this.dialogStatus = 'create'
      this.activeName = 'first'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['formData'].clearValidate()
      })
    },
    createData() {
      this.$refs['formData'].validate(valid => {
        if (valid) {
          createAssociation(this.formData)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
              this.getList()
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.activeName = 'first'
      this.dialogFormVisible = true
      queryAssociation(row.id)
        .then(res => {
          this.formData = res.data.data
        })
      this.getDetailAssociation(row)
      this.$nextTick(() => {
        this.$refs['formData'].clearValidate()
      })
    },
    updateData() {
      this.$refs['formData'].validate(valid => {
        if (valid) {
          updateAssociation(this.formData)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.formData.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.formData)
                  break
                }
              }
              this.dialogFormVisible = false
              this.getList()
              this.$notify.success({
                title: '成功',
                message: '更新用户成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDetail(row) {
      this.formData = Object.assign({}, row)
      this.dialogStatus = 'detail'
      this.activeName = 'first'
      this.dialogFormVisible = true
      this.getDetailAssociation(row)
    },
    handleDelete(row) {
      const h = this.$createElement
      this.$confirm(this.message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        message: h('p', null, [
          h('span', null, '此操作将永久删除 '),
          h('i', { style: 'color: red' }, row.name),
          h('span', null, ' ,是否继续? ')
        ])
      }).then(() => {
        deleteAssociation(row.id)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            this.getList()
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    /** ******************* 图片上传相关 *********************/
    handleAvatarSuccess(res, file) {
      this.formData.logoUrl = res.url
    },
    // 图片放大
    bigImg() {
      this.dialogVisible = true
    },
    // 图片删除
    deleteImg() {
      this.formData.logoUrl = ''
    },
    // 邀请企业成员
    handleAttributeShow() {
      this.addDialogVisible = true
      this.$nextTick(() => {
        this.qrcode()
      })
    },
    handleClose() {
      this.addDialogVisible = false
      document.getElementById('qrcode').innerHTML = ''
    },
    // 链接转成二维码
    qrcode() {
      const qrcode = new QRCode('qrcode', {
        width: 200, // 设置宽度，单位像素
        height: 200, // 设置高度，单位像素
        text: this.url // 设置二维码内容或跳转地址
      })
    },
    // 获取成员列表
    getDetailAssociation(row) {
      detailAssociation(row.id)
        .then((res) => {
          this.addList = res.data.data
        })
    },
    // 企业成员删除
    handleAttributeDelete(row) {
      const h = this.$createElement
      this.$confirm(this.message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        message: h('p', null, [
          h('span', null, '此操作将移除该成员 '),
          h('i', { style: 'color: red' }, row.name),
          h('span', null, ' ,是否继续? ')
        ])
      }).then(() => {
        deleteUser(row.id)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.addList.indexOf(row)
            this.addList.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    // 复制功能
    copyLink() {
      const clipboard = new Clipboard('.btn')
      clipboard.on('success', e => {
        this.$notify.success({
          title: '成功',
          message: '复制成功'
        })
        clipboard.destroy() // 使用destroy可以清楚缓存
      })
      clipboard.on('error', e => {
        this.$notify.error({
          title: '失败',
          message: '复制失败'
        })
        clipboard.destroy()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.contentRecord {
  ::v-deep img {
    width: 100%;
  }
}

.el-dialog {
  -webkit-box-shadow: none !important;
}

.el-dialog__body {
  padding: 10px 30px 20px 30px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.logoUrlIcon {
  position: absolute;
  top: 2px;
  z-index: 999;
  background-color: rgba(0, 0, 0, 0.3);
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.introduction .el-dialog {
  padding-bottom: 20px;
  width: 700px;
}
</style>
